package com.ruoyi.quartz.task;


import com.alibaba.fastjson.JSONObject;
import com.ruoyi.bizsys.domain.ProductInfo;
import com.ruoyi.bizsys.domain.SmsTask;
import com.ruoyi.bizsys.domain.SmsTemplate;
import com.ruoyi.bizsys.service.ISmsTaskService;
import com.ruoyi.bizsys.service.ISmsTemplateService;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.market.domain.MarketUser;
import com.ruoyi.market.service.IMarketUserService;
import com.ruoyi.market.util.MarketSmsTemplateUtil;
import com.ruoyi.market.util.MarketUserLabel;
import com.ruoyi.market.vo.MarketParamVo;
import com.ruoyi.market.vo.MarketUserVo;
import com.ruoyi.sms.domain.SmsSendData;
import com.ruoyi.system.service.ISysConfigService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 短信召回任务
 * @author pengguochao
 * @date: 2022-01-17
 */
@Slf4j
@AllArgsConstructor
@Component("smsRecallTask")
public class SmsRecallTask {

    @Autowired
    IMarketUserService marketUserService;

    @Autowired
    ISmsTemplateService smsTemplateService;

    @Autowired
    ISmsTaskService smsTaskService;

    @Autowired
    ISysConfigService sysConfigService;

    /**
     *  营销短信通知类型
     */
    public static final String SMS_NOTICE_TYPE = "market";

    /**
     *  国别号
     */
    public static final String SMS_COUNTRY_CODE = "+234";

    public static String PARAM_MARK = "#";

    /**
     * 短信召回
     * 1、已注册未提交实名
     * 2、已实名成功未提交授信
     * 3、已授信成功未提交绑卡
     */
    public void execute(){
        //注册未实名
        MarketParamVo marketParamVo = initQueryParam();
        List<MarketUserVo> appUserList = marketUserService.selectNoRealNameList(marketParamVo);
        createRecallRegisterPwd(appUserList);
        log.info("-------- 注册未实名 的用户名单有  ： "+ appUserList.size() + " 条");
        //实名成功 未授信
        List<MarketUserVo> realNameAuthList = marketUserService.selectRealNameAuthList(marketParamVo);
        createMarketSmsTask(realNameAuthList,MarketSmsTemplateUtil.RECALL_KYC_SUCCESS);
        log.info("-------- 实名成功 未授信 的用户名单有  ： "+ realNameAuthList.size() + " 条");

        //授信成功未绑卡
        marketParamVo.setApplyStatus(1);
        List<MarketUserVo> creditApplyList = marketUserService.selectCreditApplyList(marketParamVo);
        createMarketSmsTask(creditApplyList,MarketSmsTemplateUtil.RECALL_CREDIT_SUCCESS);
        log.info("-------- 授信成功未绑卡 的用户名单有  ： "+ creditApplyList.size() + " 条");

        //授信成功为提现
        List<MarketUserVo> creditApplyLoanIouList = marketUserService.selectCreditLoanIouList(marketParamVo);
        createMarketSmsTask(creditApplyLoanIouList, BizConstants.SMS_TYPE_MAIN_NOWDRW_0ORDISCINT);
        log.info("-------- 授信成功未提现 的用户名单有  ： "+ creditApplyLoanIouList.size() + " 条");
    }

    /**
     * 注册未实名  注册成功有密码/无密码 生成短信任务
     * @param appUserList
     * @return
     */
    public int createRecallRegisterPwd(List<MarketUserVo> appUserList) {
        List<SmsTask> smsTaskList = new ArrayList<>();
        SmsSendData smsData_pdw = SmsSendData.builder()
                .smsType(MarketSmsTemplateUtil.RECALL_REGISTER_PWD)
                .noticeType(SMS_NOTICE_TYPE)
                .build();
        JSONObject smsParam_pwd = getSmsContnet(smsData_pdw);
        SmsSendData smsData_nopwd = SmsSendData.builder()
                .smsType(MarketSmsTemplateUtil.RECALL_REGISTER_NOPWD)
                .noticeType(SMS_NOTICE_TYPE)
                .build();
        JSONObject smsParam_nopwd = getSmsContnet(smsData_nopwd);
        for(int i=0; i<appUserList.size(); i++){
            SmsTask smsTask = new SmsTask();
            smsTask.setCountryCode(SMS_COUNTRY_CODE);
            smsTask.setPhone(appUserList.get(i).getPhoneNumber());
            if(appUserList.get(i).getPassword() !=null) {
                smsTask.setSmsType(MarketSmsTemplateUtil.RECALL_REGISTER_PWD);
                smsTask.setContent(smsParam_pwd.getString("content"));
                smsTask.setTemplateId(smsParam_pwd.getString("templateId"));
            }else{
                smsTask.setSmsType(MarketSmsTemplateUtil.RECALL_REGISTER_NOPWD);
                smsTask.setContent(smsParam_nopwd.getString("content"));
                smsTask.setTemplateId(smsParam_nopwd.getString("templateId"));
            }
            smsTask.setNoticeType(SMS_NOTICE_TYPE);
            smsTaskList.add(smsTask);

            if(i == 999 || i== appUserList.size()-1){
                smsTaskService.batchAdd(smsTaskList);
                smsTaskList=  new ArrayList<>();
            }
        }
        return appUserList.size();
    }

    /**
     *  1、实名成功 未授信
     *  2、授信成功未绑卡
     * @param marketUserVoList
     * @param type
     * @return
     */
    public int createMarketSmsTask(List<MarketUserVo> marketUserVoList,String type){
        List<SmsTask> smsTaskList = new ArrayList<>();
        SmsSendData smsData = SmsSendData.builder()
                .smsType(type)
                .noticeType(SMS_NOTICE_TYPE)
                .build();
        for(int i=0; i<marketUserVoList.size(); i++) {
            MarketUserVo marketUserVo = marketUserVoList.get(i);
            JSONObject smsJson = new JSONObject();
            switch (type){
                case MarketSmsTemplateUtil.RECALL_KYC_SUCCESS:// 实名成功 未授信
                    smsJson.put("lastName",marketUserVo.getLastName());
                    smsJson.put("creditlimit",marketUserVo.getCreditLine());
                    marketUserVo.setUserLabel(MarketUserLabel.VERIFED_BUT_NOT_APPLIED);
                    break;
                case MarketSmsTemplateUtil.RECALL_CREDIT_SUCCESS:// 授信成功未绑卡
                    smsJson.put("lastName",marketUserVo.getLastName());
                    smsJson.put("creditlimit",marketUserVo.getCreditLine());
                    marketUserVo.setUserLabel(MarketUserLabel.APPLICATION_SUCCESS_NO_CARD_BOUND);
                    break;
                case BizConstants.SMS_TYPE_MAIN_NOWDRW_0ORDISCINT:// 授信成功未提现#last_name##credit_line#=授信额度#credit_rating#=用户等级#产品期数#=可借期数、#tags#=金融产品名称
                    smsJson.put("last_name",marketUserVo.getLastName());
                    smsJson.put("credit_line",marketUserVo.getCreditLine());
                    smsJson.put("credit_rating",sysConfigService.selectConfigKey(marketUserVo.getCreditRating()));
                    smsJson.put("productperiod",marketUserVo.getPeriodNum());
                    String split = marketUserVo.getTags();
                    BigDecimal multiply = ((marketUserVo.getShowInterestRate().subtract(marketUserVo.getInterestRate())).divide(marketUserVo.getShowInterestRate(),BigDecimal.ROUND_HALF_UP)).multiply(BigDecimal.valueOf(100)).setScale(0,BigDecimal.ROUND_HALF_UP);
                    //BigDecimal multiply = marketUserVo.getShowInterestRate().subtract(marketUserVo.getInterestRate()).divide(marketUserVo.getShowInterestRate(),BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
                    smsJson.put("tags", split.contains("-1") ? "0 interest" : multiply+"% interest discount");
                    break;
            }
            smsData.setSmsParam(smsJson);
            JSONObject smsParam = getSmsContnet(smsData);

            SmsTask smsTask = new SmsTask();
            smsTask.setCountryCode(SMS_COUNTRY_CODE);
            smsTask.setPhone(marketUserVo.getPhoneNumber());
            smsTask.setSmsType(type);
            smsTask.setContent(smsParam.getString("content"));
            smsTask.setNoticeType(SMS_NOTICE_TYPE);
            smsTask.setTemplateId(smsParam.getString("templateId"));
            if(null !=smsTask.getPhone() && null !=smsTask.getSmsType()){
                smsTaskList.add(smsTask);
            }
            if(i == 999 || i== marketUserVoList.size()-1){
                smsTaskService.batchAdd(smsTaskList);
                smsTaskList=  new ArrayList<>();
            }
        }
        return marketUserVoList.size();
    }

    /**
     * 短信任务生成
     */
    public JSONObject getSmsContnet(SmsSendData smsData) {
        JSONObject jsonObject = new JSONObject();
        SmsTemplate smsTemplate = new SmsTemplate();
        smsTemplate.setNoticeType(smsData.getNoticeType());
        smsTemplate.setSmsType(smsData.getSmsType());
        smsTemplate.setState("1");
        List<SmsTemplate> smsTemplateList = smsTemplateService.selectSmsTemplateList(smsTemplate);
        String content = smsTemplateList.get(0).getTemplateContent();

        if (content.contains(PARAM_MARK)) {
            content = replaceTemplateParams(content, smsData.getSmsParam());
        }
        jsonObject.put("content",content);
        jsonObject.put("templateId",smsTemplateList.get(0).getTemplateId());
        return jsonObject;
    }

    /**
     * 获取前 2、14 小时 时间
     * @return
     */
    public static MarketParamVo initQueryParam(){
        MarketParamVo marketParamVo= new MarketParamVo();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.add(Calendar.HOUR_OF_DAY, -14);
        marketParamVo.setCreateTime(now.getTime());
        now.setTime(date);
        now.add(Calendar.HOUR_OF_DAY, -2);
        marketParamVo.setEndTime(now.getTime());
        log.info("------- 获取 " + sdf.format(marketParamVo.getCreateTime())
                + "----" + sdf.format(marketParamVo.getEndTime()) +" 需要发送召回短信的数据");
        return marketParamVo;
    }


    protected String replaceTemplateParams(String templateContent, JSONObject dataJson) {
        String smsContent = templateContent;

        Iterator<String> iterator = (Iterator<String>) dataJson.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String value = dataJson.getString(key);
            if (smsContent.contains(key)) {
                smsContent = smsContent.replace(PARAM_MARK + key + PARAM_MARK, value);
            }
        }
        return smsContent;
    }

}
